import React, { useCallback, useMemo, useRef } from 'react';
import { SmartGrid } from 'gantd';
import { connect } from 'umi';
import type { OnReady, GridApi } from 'gantd/lib/grid';
import type { SmartTableProps } from 'gantd/lib/smart-grid/interface';
import { commonText } from '@/utils/utils';
import { XBomGridSchema } from '@/pages/xbommanage/SpecialOrder/Schema';
import styles from './module.less';

const { TableFieldsSchemaWithStyle } = XBomGridSchema;

export interface BOMGridProps<T> extends Omit<SmartTableProps<T>, 'tableKey' | 'gridKey' | 'schema'> {
  title?: string;
  gridKey?: string;
  editable: boolean;
  gridSchema: any[];
}

const OrderTable = function BOMGrid<T>(props: BOMGridProps<T>) {
  const { onReady, gridKey, gridLoading, dataSource = [], type, ...restProps } = props;
  const api = useRef<GridApi>();

  const onGridRady = useCallback<OnReady>(
    (params, gridmanager) => {
      api.current = params.api;
      onReady?.(params, gridmanager);
    },
    [onReady],
  );

  const gridSchema = useMemo(() => {
    if (type === 'copyOrder') {
      // 订单复制页面，mbom工程师接口未查询出来
      return TableFieldsSchemaWithStyle.filter((item) => item?.fieldName !== 'authPersonsStr');
    } else {
      return TableFieldsSchemaWithStyle;
    }
  }, [type]);

  return (
    <div className={styles['bom-wrapper']}>
      <SmartGrid
        gridKey={gridKey}
        rowkey={(data: any) => data.id + ''}
        schema={gridSchema}
        onReady={onGridRady}
        serialNumber
        boxColumnIndex={['id']}
        title={commonText.smartGridTitleText}
        dataSource={dataSource}
        loading={gridLoading}
        {...restProps}
      />
    </div>
  );
};

export default connect()(OrderTable) as <T>(props: BOMGridProps<T>) => React.ReactElement;
